// 移动端答题详情逻辑

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// 检查填空题答案
function checkFillInAnswer(userAnswer, correctAnswer, keywords = '') {
    if (!userAnswer || !correctAnswer) {
        return false;
    }
    
    // 清理用户答案
    userAnswer = userAnswer.trim().toLowerCase();
    
    // 处理多个正确答案（用逗号分隔）
    const correctAnswers = correctAnswer.split(',').map(ans => ans.trim().toLowerCase());
    
    // 处理关键词（用逗号分隔），确保keywords不为null或undefined
    const keywordList = (keywords || '').split(',').map(kw => kw.trim().toLowerCase()).filter(kw => kw);
    
    // 检查是否匹配正确答案
    if (correctAnswers.includes(userAnswer)) {
        return true;
    }
    
    // 检查是否匹配关键词
    if (keywordList.includes(userAnswer)) {
        return true;
    }
    
    // 模糊匹配（去除空格、标点符号）
    const userClean = userAnswer.replace(/[^\w\u4e00-\u9fff]/g, '');
    
    for (const ans of correctAnswers) {
        const ansClean = ans.replace(/[^\w\u4e00-\u9fff]/g, '');
        if (userClean === ansClean) {
            return true;
        }
    }
    
    for (const kw of keywordList) {
        const kwClean = kw.replace(/[^\w\u4e00-\u9fff]/g, '');
        if (userClean === kwClean) {
            return true;
        }
    }
    
    return false;
}

// 加载答题结果
function loadQuizResult() {
    const resultData = sessionStorage.getItem('quizResult');
    
    if (!resultData) {
        showEmptyState();
        return;
    }
    
    try {
        const result = JSON.parse(resultData);
        displayResult(result);
    } catch (error) {
        console.error('解析答题结果失败:', error);
        showEmptyState();
    }
}

// 显示空状态
function showEmptyState() {
    document.querySelector('.score-overview').innerHTML = `
        <div class="empty-container">
            <div class="empty-icon">📝</div>
            <div class="empty-text">暂无答题记录</div>
            <button class="btn btn-primary" onclick="window.location.href='/quiz'">
                开始答题
            </button>
        </div>
    `;
}

// 显示结果
function displayResult(result) {
    const { questions, userAnswers, fillInAnswers, score, correctCount, wrongCount, timeElapsed } = result;
    
    // 更新概览
    document.getElementById('scoreValue').textContent = score;
    document.getElementById('correctCount').textContent = correctCount;
    document.getElementById('wrongCount').textContent = wrongCount;
    document.getElementById('timeUsed').textContent = formatTime(timeElapsed);
    
    // 显示题目详情
    const questionsList = document.getElementById('questionsList');
    questionsList.innerHTML = '';
    
    questions.forEach((question, index) => {
        const userAnswer = userAnswers[index];
        const fillInAnswer = fillInAnswers ? fillInAnswers[index] : '';
        const isCorrect = question.question_type === 'fill_in_blank' ? 
            checkFillInAnswer(fillInAnswer, question.fill_in_answer, question.fill_in_keywords) :
            Number(userAnswer) === Number(question.correct);
        
        const questionDiv = createQuestionElement(question, index, userAnswer, fillInAnswer, isCorrect);
        questionsList.appendChild(questionDiv);
    });
    
    // 渲染所有数学公式
    setTimeout(() => {
        renderMath(document.body);
    }, 100);
}

// 创建题目元素
function createQuestionElement(question, index, userAnswer, fillInAnswer, isCorrect) {
    const div = document.createElement('div');
    div.className = 'question-item';
    
    const labels = ['A', 'B', 'C', 'D'];
    
    // 题目头部
    const headerHtml = `
        <div class="question-header">
            <span class="question-number">第 ${index + 1} 题</span>
            <span class="question-status ${isCorrect ? 'correct' : 'wrong'}">
                ${isCorrect ? '✓ 答对了' : '✗ 答错了'}
            </span>
        </div>
    `;
    
    // 题目内容
    const titleHtml = `
        <div class="question-title">${renderMarkdown(question.title)}</div>
    `;
    
    // 题目图片
    const imageHtml = question.question_image ? `
        <img src="${question.question_image}" class="question-image" alt="题目图片">
    ` : '';
    
    // 选项列表或填空题答案
    let optionsHtml = '';
    let answerInfoHtml = '';
    
    if (question.question_type === 'fill_in_blank') {
        // 填空题显示
        optionsHtml = `
            <div class="fill-in-answer-display">
                <div class="answer-item">
                    <span class="answer-label">你的答案：</span>
                    <span class="answer-value ${isCorrect ? 'correct' : 'wrong'}">
                        ${fillInAnswer || '未作答'}
                    </span>
                </div>
                <div class="answer-item">
                    <span class="answer-label">参考答案：</span>
                    <span class="answer-value correct">${question.fill_in_answer}</span>
                </div>
                ${question.fill_in_keywords ? `
                    <div class="answer-item">
                        <span class="answer-label">关键词：</span>
                        <span class="answer-value keywords">${question.fill_in_keywords}</span>
                    </div>
                ` : ''}
            </div>
        `;
        answerInfoHtml = '';
    } else {
        // 选择题显示
        optionsHtml = '<div class="options-list">';
        question.options.forEach((option, optIndex) => {
            // 确保 userAnswer 和 question.correct 都是数字类型
            const userAnswerNum = userAnswer !== null ? Number(userAnswer) : null;
            const correctAnswerNum = Number(question.correct);
            
            const isUserAnswer = userAnswerNum === optIndex;
            const isCorrectAnswer = correctAnswerNum === optIndex;
            
            let optionClass = 'option-item';
            if (isUserAnswer && !isCorrect) {
                optionClass += ' user-answer wrong';
            } else if (isUserAnswer) {
                optionClass += ' user-answer';
            }
            if (isCorrectAnswer) {
                optionClass += ' correct-answer';
            }
            
            let optionContent = '';
            const labels = ['A', 'B', 'C', 'D'];
            const optionImageKey = `option_${labels[optIndex].toLowerCase()}_image`;
            if (question[optionImageKey]) {
                optionContent = renderMarkdown(option || '') + 
                              `<img src="${question[optionImageKey]}" class="option-image" alt="选项图片">`;
            } else {
                optionContent = renderMarkdown(option);
            }
            
            optionsHtml += `
                <div class="${optionClass}">
                    <div class="option-label">${labels[optIndex]}</div>
                    <div class="option-text">${optionContent}</div>
                </div>
            `;
        });
        optionsHtml += '</div>';
        
        // 答案信息
        const userAnswerNum = userAnswer !== null ? Number(userAnswer) : null;
        const correctAnswerNum = Number(question.correct);
        
        answerInfoHtml = `
            <div class="answer-info">
                <div class="answer-item">
                    <span class="answer-label">你的答案：</span>
                    <span class="answer-value user-answer">
                        ${userAnswerNum !== null ? labels[userAnswerNum] : '未作答'}
                    </span>
                </div>
                <div class="answer-item">
                    <span class="answer-label">正确答案：</span>
                    <span class="answer-value correct">${labels[correctAnswerNum]}</span>
                </div>
            </div>
        `;
    }
    
    // 解析部分
    const explanationHtml = question.explanation ? `
        <div class="explanation-section">
            <div class="explanation-title">💡 答案解析</div>
            <div class="explanation-content">
                ${renderMarkdown(question.explanation)}
                ${question.explanation_image ? `<img src="${question.explanation_image}" class="explanation-image" alt="解析图片">` : ''}
            </div>
        </div>
    ` : '';
    
    div.innerHTML = headerHtml + titleHtml + imageHtml + optionsHtml + answerInfoHtml + explanationHtml;
    
    return div;
}

// 格式化时间
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 设置当前导航项为激活状态
function setActiveNav() {
    const path = window.location.pathname;
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('href') === path) {
            item.classList.add('active');
        }
    });
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', () => {
    loadQuizResult();
    setActiveNav();
});

